package repository

import (
	"fitness/go-admin/internal/model"
	"time"

	"gorm.io/gorm"
)

type OperationLogRepository interface {
	Create(log *model.OperationLog) error
	GetByID(id uint) (*model.OperationLog, error)
	List(req *model.OperationLogListReq) ([]*model.OperationLogListItem, int64, error)
	GetDetailByID(id uint) (*model.OperationLogDetailResp, error)
	Delete(id uint) error
	DeleteBatch(ids []uint) error
}

type operationLogRepository struct {
	db *gorm.DB
}

func NewOperationLogRepository(db *gorm.DB) OperationLogRepository {
	return &operationLogRepository{db: db}
}

// Create 创建操作日志
func (r *operationLogRepository) Create(log *model.OperationLog) error {
	return r.db.Create(log).Error
}

// GetByID 根据ID获取操作日志
func (r *operationLogRepository) GetByID(id uint) (*model.OperationLog, error) {
	var log model.OperationLog
	err := r.db.First(&log, id).Error
	return &log, err
}

// List 获取操作日志列表
func (r *operationLogRepository) List(req *model.OperationLogListReq) ([]*model.OperationLogListItem, int64, error) {
	var total int64
	var logs []*model.OperationLogListItem

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	if req.PageSize > 100 {
		req.PageSize = 100 // 限制最大分页大小
	}

	// 构建查询
	query := r.db.Table("operation_logs")

	// 用户名筛选
	if req.Username != "" {
		query = query.Where("username LIKE ?", "%"+req.Username+"%")
	}

	// 操作类型筛选
	if req.Action != "" {
		query = query.Where("action = ?", req.Action)
	}

	// 资源类型筛选
	if req.Resource != "" {
		query = query.Where("resource = ?", req.Resource)
	}

	// IP地址筛选
	if req.IP != "" {
		query = query.Where("ip LIKE ?", "%"+req.IP+"%")
	}

	// 日期范围筛选
	if req.StartDate != "" {
		startTime, err := time.Parse("2006-01-02", req.StartDate)
		if err == nil {
			query = query.Where("created_at >= ?", startTime)
		}
	}
	if req.EndDate != "" {
		endTime, err := time.Parse("2006-01-02", req.EndDate)
		if err == nil {
			// 结束日期加一天，包含当天所有记录
			endTime = endTime.AddDate(0, 0, 1)
			query = query.Where("created_at < ?", endTime)
		}
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	err := query.Offset(offset).Limit(req.PageSize).Order("created_at DESC").Scan(&logs).Error

	return logs, total, err
}

// GetDetailByID 根据ID获取操作日志详情
func (r *operationLogRepository) GetDetailByID(id uint) (*model.OperationLogDetailResp, error) {
	var detail model.OperationLogDetailResp

	err := r.db.Table("operation_logs").
		Where("id = ?", id).
		Scan(&detail).Error

	if err != nil {
		return nil, err
	}

	// 检查是否找到日志
	if detail.ID == 0 {
		return nil, gorm.ErrRecordNotFound
	}

	return &detail, nil
}

// Delete 删除操作日志
func (r *operationLogRepository) Delete(id uint) error {
	return r.db.Delete(&model.OperationLog{}, id).Error
}

// DeleteBatch 批量删除操作日志
func (r *operationLogRepository) DeleteBatch(ids []uint) error {
	return r.db.Where("id IN ?", ids).Delete(&model.OperationLog{}).Error
}
